random
¶random.choice()
¶import random
fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)
print(selection)
mango
random.randint()
¶import random
print(random.randint(1, 10))
2
random.random()
¶print(random.random())
0.5803070027788184
If you need a random float between 0 and 100, just scale the random number:
print(random.random() * 100)
40.015655234506866
random.sample()
¶name = 'George Washington'
print(random.sample(name, 2))
['r', 'G']
print(random.sample(name, 10))
['o', 'n', 'i', 'e', 's', 't', ' ', 'a', 'n', 'g']
print(''.join(random.sample(name, len(name))))
sW nieGgerognaoth
random.sample
can be used to get a random sample from a collection.
If you sample all the items in the collection, you essentially get a shuffled version of the data.
import random
def shuffle(string):
"""
Use random.sample to get the letters in the string in a random order.
Then join the letters together with the empty string.
"""
shuffled_letters = random.sample(string, len(string))
return ''.join(shuffled_letters)
shuffle('12345')
'32154'
shuffle('CS110')
'1CS10'
apples.py
¶Write a program that takes a frequency (a number between 0 and 1) and a phrase as commandline arguments.
Randomly inject "umm" into a given sentence at the given frequency and print the result.
umm.py
¶random
choice
randint
random
sample
random.sample